package com.foot.travel.activity;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

import com.foot.travel.R;
import com.foot.travel.R.id;
import com.foot.travel.R.layout;
import com.foot.travel.R.raw;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.koalac.ironman.common.module.ModuleActivity;
import com.koalac.ironman.scan.camera.CameraManager;
import com.koalac.ironman.scan.decoding.CaptureActivityHandler;
import com.koalac.ironman.scan.decoding.InactivityTimer;
import com.koalac.ironman.scan.view.ViewfinderView;
import com.koalac.ironman.util.KeyUtil;
import com.koalac.ironman.util.StringUtils;
import com.koalac.ironman.widget.LoadingDialog;
import com.koalac.ironman.widget.MyAlertDialog;

/**
 * Initial the camera
 * 
 * @author Ryan.Tang
 */
public class ScanCaptureActivity extends ModuleActivity implements Callback {

	private SurfaceView surfaceView;
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;
	private Timer timer = new Timer(true);//扫描超时的定时器
	private Handler localHandler = new Handler(){
		 @Override
		  public void handleMessage(Message message) {
		    switch (message.what) {
		    case KeyUtil.SCAN_TIME_OUT:
		    	timer.cancel();
		    	CameraManager.get().stopPreview();
		    	MyAlertDialog.showConfirmAlertDialog(ScanCaptureActivity.this, "", "扫描失败！",new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ScanCaptureActivity.this.finish();
					}
					
				});
		    	break;
		    }
		 }
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setNavigationTitle(KeyUtil.SCAN_CAPTURE_ACTIVITY_TITLE);
		this.setBackButtonVisibility(true);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		ScanCaptureActivity.this.finish();
	}

	@Override
	protected void initLayout(ViewGroup rootContentView) {
		final LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.scan_capture, null);
		rootContentView.addView(view);

		// ViewUtil.addTopView(getApplicationContext(), this,
		// R.string.scan_card);
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		timer.cancel();
		super.onDestroy();
	}

	/**
	 * ����ɨ����
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		 playBeepSoundAndVibrate();
		timer.cancel();
		String resultString = result.getText();
		if (isCorrectContent(resultString)) {
			getSationContent(resultString);
		} else {
			MyAlertDialog.showConfirmAlertDialog(ScanCaptureActivity.this, "", "扫描错误！",new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					ScanCaptureActivity.this.finish();
				}
			});
			
		}
	}

	/**
	 * 把二维码的内容作为参数进行网络请求
	 * 
	 * @param content
	 */
	private void getSationContent(String content) {
		CameraManager.get().stopPreview();//已经在请求,停止预览
		final LoadingDialog p = LoadingDialog.createLoadingDialog(ScanCaptureActivity.this, "", "扫描内容处理中...");
		p.show();
//		CSign cSign = new CSign();
//		cSign.setContent(content);
		checkTimeOut();
	}

	/**
	 * 检查扫描内容是否正确
	 * 
	 * @param content
	 * @return
	 */
	private boolean isCorrectContent(String content) {
		if (content == null || content.equals("")) {
			return false;
		}
		String[] contentArray = content.split("_");
//		if (contentArray.length == 3) {
//			if (StringUtils.isNumberString(contentArray[0])
//					&& StringUtils.isNumberString(contentArray[1])) {
//				return true;
//			} else {
//				return false;
//			}
//		}
		return false;
	}
	/**
	 * 限定网络请求时间为10秒,超时警告
	 */
	private void checkTimeOut(){
		TimerTask task = new TimerTask() {
			
			@Override
			public void run() {
				Message msg = new Message();
				msg.what= KeyUtil.SCAN_TIME_OUT;
				localHandler.sendMessage(msg);
			}
		};
		timer = new Timer(true);
		timer.schedule(task, 10000);//延迟10秒执行
	}
	
	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

}